<template>
    <!-- 外层div -->
    <div class="sealCutting">
        <!-- card卡片 -->
        <el-card class="box-card">
            <!-- 篆刻头部<新增 删除 关键字 查询 重置> -->
            <div class="ContributionsHead">
                <!-- 新增 删除按钮 -->
                <div>
                    <el-button type="primary" @click="add">新增</el-button>
                    <el-button @click="delteAllMethod">删除</el-button>
                </div>
                <!-- 新增对话框 -->
                <el-dialog
                 v-model="dialogFormVisible" title="新增">
                    <el-form 
                    :rules="rules"
                    ref="ruleFormRef"
                    :model="addForm">
                        <el-form-item label="印章正面" prop="sealFront" :label-width="formLabelWidth">
                            <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/"
                                :show-file-list="false" :on-success="handleAvatarSuccess">
                                <img v-if="addForm.sealFront" :src="addForm.sealFront" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon">+</i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="印章反面" prop="sealReverse" :label-width="formLabelWidth">
                            <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/"
                                :show-file-list="false" :on-success="handleSuccess" >
                                <img v-if="addForm.sealReverse" :src="addForm.sealReverse" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon">+</i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="所属分类" prop="category_id" :label-width="formLabelWidth">
                            <el-cascader
                                v-model="addForm.category_id"
                                :options="cateData"
                                :props="cascadeDate" 
                                />
                        </el-form-item>
                        <el-form-item label="印章名称" prop="sealName" :label-width="formLabelWidth">
                            <!-- 工具栏 -->
                            <div class="text">
                                <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig"
                                    style="border-bottom: 1px solid #ccc" />
                                <!-- 编辑器 -->
                                <Editor v-model="valueHtml" :defaultConfig="editorConfig"
                                    style="height: 350px; overflow-y: hidden;" @onCreated="handleCreated" />
                            </div>

                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">
                                保存
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
                <!--搜索条件筛选栏  -->
                <div class="ContributionsHeadCentre">
                    <el-space>
                        <el-input v-model="ContributionsSearchTitle" placeholder="请输入关键字" />
                    </el-space>
                        <el-space>
                            <el-cascader
                                v-model="selectId"
                                :options="cateData"
                                :props="selectCascadeDate" 
                                />
                        </el-space>
                </div>
                <!-- 查询 重置按钮 -->
                <div>
                    <el-button type="primary" @click="searchMethod" :icon="Search">查询</el-button>
                    <el-button :icon="RefreshLeft" @click="reset">重置</el-button>
                </div>
            </div>
            <!-- 页面主体表格 -->
            <div>
                <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="sealName" label="印章名称" >
                        <template #default="scope">
                            <div v-html="scope.row.sealName"></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="category__name" label="所属分类" />
                    <el-table-column label="印章正面">
                        <template #default="scope">
                            <div class="demo-image__preview">
                                <el-image style="width: 100px; height: 100px" :src="scope.row.sealFront" :zoom-rate="1.2"
                                    :preview-src-list="[scope.row.sealFront]" :initial-index="0" fit="cover" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="印章反面">
                        <template #default="scope">
                            <div class="demo-image__preview">
                                <el-image style="width: 100px; height: 100px" :src="scope.row.sealReverse" :zoom-rate="1.2"
                                    :preview-src-list="[scope.row.sealReverse]" :initial-index="0" fit="cover" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="updateTime" label="更新时间" >
                        <template #default="scope">
                            {{ filterTime(scope.row.updateTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <!-- 编辑与删除按钮 -->
                        <template #default="scoped">
                            <el-button link type="primary" size="small" @click="edit(scoped.row)">编辑</el-button>
                            <el-button link type="danger" size="small" @click="deleteMethod(scoped.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="page">
                <el-row>
                    <el-col :span="20">

                    </el-col>
                    <el-col :span="4">
                        <el-pagination v-model:current-page="currentPage3" v-model:page-size="pageSize3" :small="small"
                            background layout="prev, pager, next, jumper" :total="totalNum"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </el-col>
                </el-row>
            </div>
            <UpdateVue :updateDisable = "updateDisable" 
            @editTrue="editTrue"
            :resloveObj="resloveObj"></UpdateVue>
        </el-card>
    </div>
</template>

<script setup>
import UpdateVue from './update.vue'
import { ref } from 'vue'
import moment from "moment"
import service from '@/utils/request.ts'
// 引入 搜索和重置的图标
import { Search, RefreshLeft } from '@element-plus/icons-vue'
// 图片上传图标
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import Space from 'element-plus/es/components/space/src/space'
const cascadeDate = {value:"id",label:"name",checkStrictly:true,emitPath:false}
const selectCascadeDate = {value:"id",label:"name",checkStrictly:false,emitPath:false}
const totalNum = ref(0) 
const selectId = ref([])
const editTrue = ()=>{
    getDataList()
    updateDisable.value = false
}
const resloveObj = ref(0)
const ruleFormRef = ref()
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value=false
}
const rules = reactive({
    category_id: [
    { required: true, message: '请选择分类！', trigger: 'blur' },
  ],
  sealFront:[
    { required: true, message: '请上传印章正面！', trigger: 'blur' },
  ],
  sealReverse:[
    { required: true, message: '请上传印章背面！', trigger: 'blur' },
  ],
  sealName:[{ required: true, message: '请输入名称！', trigger: 'blur' },]
})
const submitForm = async (formEl) => {
addForm.sealName = valueHtml.value
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addMethod()
    }
  })
}
//重置
const reset = ()=>{
    selectId.value = []
    pageSize3.value = 5
    currentPage3.value = 1
    getDataList()
}
// 过滤方法（格式化时间数据）
const filterTime = (time) => {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
}
//删除全部的方法
const delteAllMethod = async ()=>{
    const {code,msg} =  await service.post(`/api/spread/spreadDelAll`,{'list':ids.value})
    if(code===200){
        ElMessage(msg)
        getDataList()
    }
}
// //过滤文本
const filterTexgt = (text)=>{
    return text.replace(/<[^>]+>|&[^>]+;/g, '').trim()
}
const searchMethod = ()=>{
    getDataList()
}
const handleAvatarSuccess = (obj)=>{
    addForm.sealFront = obj.path
}
const handleSuccess = (obj)=>{
    addForm.sealReverse = obj.path
}
//添加对话框
const dialogFormVisible = ref(false)
const addMethod = async ()=>{
    const {code,mesg} =  await service.post(`/api/sealcutting/sealCutting`,addForm)
    if(code===200){
        ElMessage(mesg)
        getDataList()
        valueHtml.value=''
        addForm.sealFront=''
        addForm.sealReverse=''
        addForm.category_id=''
    }
    dialogFormVisible.value = false
}
const addForm = reactive({
    sealName:'',
    sealFront:'',
    sealReverse:'',
    category_id:''
})
const cateData = ref([])
const getCateList = async ()=>{
    const {code,data} = await service.get(`/api/classify/classfiy/`)
    if(code==200){
        cateData.value = data
    }
}

const getDataList = async ()=>{
    const {data,code,total} =  await service.get(`/api/sealcutting/sealCutting?keyword=${ContributionsSearchTitle.value}&page=${currentPage3.value}&pagesize=${pageSize3.value}&typeid=${selectId.value.toString()}`)
    if(code===200){
        console.log(data);
        totalNum.value = total
        tableData.value = data
    }
}
//初始化页面
onMounted(()=>{
    getDataList()
    getCateList()
})

const deleteMethod = (id)=>{
    ElMessageBox.confirm(
    '确定删除？',
    '删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        const {code,mesg} =  await service.delete(`/api/sealcutting/update/${id}`)
        if(code==200){
            ElMessage({
                type: 'success',
                message:mesg,
            })
            getDataList()
        }else{
                ElMessage({
            type: 'info',
            message: 'Delete 失败',
        })
        }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}


const formLabelWidth = '140px'
// 选择分类的初始化状态
const ContributionsSearchTitle = ref('')

// table表格数据
const tableData = ref([])
//分页参数
const currentPage3 = ref(1)
const pageSize3 = ref(5)
const small = ref(false)



// 打开对话框
const add = () => {
    dialogFormVisible.value = true
}
// 点击分页触发的函数
const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
    currentPage3.value =val
    getDataList()
}
//ids列表
const ids = ref([])
// 点击选中触发函数
const handleSelectionChange = (val) => {
    ids.value = val.map(item=>item.id)    
}

//控制弹出框显示和隐藏
const updateDisable = ref(false)
const edit = (val) => {
    resloveObj.value = val.id
    updateDisable.value = true    
}

// 富文本
const editorRef = shallowRef()
const toolbarConfig = ref()
// 内容 HTML
const valueHtml = ref('')
// 编辑器配置
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: { /* 菜单配置，下文解释 */ }
}

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style>
.el-table .el-table__cell {
    z-index: auto !important;
}
</style>
<style lang="scss"  scoped>
::v-deep(.avatar-uploader .avatar) {
  width: 178px !important;
  height: 178px !important;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
// 外层div
.sealCutting {
    padding: 1%;

    //头部div
    .ContributionsHead {
        display: flex;

        //搜索栏div
        .ContributionsHeadCentre {
            display: inline-flex;
            flex: 1;
            justify-content: flex-end;

            //select选择器
            .ContributionsHeadCentreSelect {
                margin: 0 30px 0 10px;
            }
        }
    }

}

.demo-image__error .image-slot {
    font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}

.demo-image__error .el-image {
    width: 100%;
    height: 200px;
}
.select{
    width: 30vw;
}
.text {
    width: 30vw;
}
.avatar-uploader .avatar {
  width: 178px !important;
  height: 178px !important;
  display: block;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css" >
.inputdesc {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  transition: color 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
}
.app_detail img {
  width: auto;
}
.app_detail .ql-formats {
  line-height: 22px;
}
</style>